package com.tongbo.mobilesafe.engine;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;

public class DownLoadFileTask {
	/**
	 * 下载apk文件
	 * @param path 要下载的服务器上的apk文件的路径
	 * @param filePath 保存到本地的apk文件的路径
	 * @return 下载的apk文件
	 * @throws Exception
	 */
	public static File getFile(String path,String filePath,ProgressDialog pd) throws Exception{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if(conn.getResponseCode()==200){
			int total = conn.getContentLength();
			pd.setMax(total);
			InputStream is = conn.getInputStream();
			File file = new File(filePath);
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			int progress = 0;
			while((len = is.read(buffer))!=-1){
				fos.write(buffer,0,len);
				progress += len;
				pd.setProgress(progress);
				Thread.sleep(50);
			}
			fos.flush();
			fos.close();
			is.close();
			return file;
		}
		return null;
	}
}
